<script>
import { ref, h, defineComponent, onMounted, watch } from "vue";
import { NButton, NDivider, useMessage } from "naive-ui";
import axios from "axios";
import { cloneDeep } from "lodash";
import dayjs from "dayjs";

const createColumns = ({ previewProduct, editProduct, changeStatus }) => {
  return [
    {
      title: "名称",
      key: "name",
      minWidth: 150,
    },
    {
      title: "原价",
      key: "price",
      minWidth: 100,
    },
    {
      title: "代理商价",
      key: "agentPrice",
      minWidth: 100,
    },
    {
      title: "分公司价",
      key: "companyPrice",
      minWidth: 100,
    },
    {
      title: "秒杀价",
      key: "killPrice",
      minWidth: 100,
    },
    {
      title: "秒杀开始时间",
      key: "beginTime",
      minWidth: 200,

      render(row) {
        return (
          row.beginTime && dayjs(row.beginTime).format("YYYY-MM-DD HH:mm:ss")
        );
      },
    },
    {
      title: "状态",
      key: "status",
      minWidth: 100,

      render(row) {
        return row.status === 1 ? "已上架" : "已下架";
      },
    },
    {
      title: "类型",
      key: "typeText",
      minWidth: 100,
    },
    {
      title: "排序",
      key: "sort",
      minWidth: 100,
    },
    {
      title: "库存",
      key: "stock",
      minWidth: 100,
    },
    {
      title: "简要描述",
      key: "description",
      minWidth: 200,
    },
    {
      title: "操作",
      key: "actions",
      minWidth: 200,
      fixed: "right",
      render(row) {
        return [
          h(
            NButton,
            {
              text: true,
              tag: "a",
              type: "info",
              size: "small",
              onClick: () => previewProduct(cloneDeep(row)),
            },
            { default: () => "预览" }
          ),
          h(NDivider, {
            vertical: true,
          }),
          h(
            NButton,
            {
              text: true,
              tag: "a",
              type: "info",
              size: "small",
              onClick: () => editProduct(cloneDeep(row)),
            },
            { default: () => "编辑" }
          ),
          h(NDivider, {
            vertical: true,
          }),
          h(
            NButton,
            {
              text: true,
              tag: "a",
              type: "info",
              size: "small",
              onClick: () => changeStatus(cloneDeep(row)),
            },
            {
              default: () => {
                if (row.status === 1) {
                  return "下架";
                } else {
                  return "上架";
                }
              },
            }
          ),
        ];
      },
    },
  ];
};

export default defineComponent({
  setup() {
    const message = useMessage();
    const data = ref([]);
    const formRef = ref();
    const addPrdouct = ref({});
    const currentPrdouct = ref({});
    const showModalRef = ref(false);
    const showPreviewModalRef = ref(false);
    const showPhoneModalRef = ref(false);
    const previewImageUrlRef = ref("");
    const fileList = ref([]);
    const detailFileList = ref([]);
    const srcList = ref([]);
    const mainSrcList = ref([]);

    const initQueryData = {
      name: null,
      status: null,
    };
    const queryData = ref(cloneDeep(initQueryData));
    const statusOptions = [
      {
        label: "已上架",
        value: 1,
      },
      {
        label: "已下架",
        value: 0,
      },
    ];

    watch(
      () => addPrdouct.value.type,
      (newValue, oldValue) => {
        console.log(newValue);
        if (newValue == 4) {
          addPrdouct.value.price = 0;
        } else {
          // addPrdouct.value.price = "";
        }
      }
    );

    function handlePreview(file) {
      const { url } = file;
      previewImageUrlRef.value = url;
      showPreviewModalRef.value = true;
    }

    function handleFile({ file, event }) {
      file.url = JSON.parse(event.target.response).data;
    }

    function handleDetailFile({ file, event }) {
      file.url = JSON.parse(event.target.response).data;
    }

    onMounted(() => {
      findList({});
    });

    function findList(queryData) {
      axios({
        method: "post",
        url: "/productInfo/findList",
        data: queryData,
      }).then(function (response) {
        if (response.data.code === 200) {
          data.value = response.data.data;
        }
      });
    }

    return {
      data,
      queryData,
      addPrdouct,
      currentPrdouct,
      statusOptions,
      handlePreview,
      handleFile,
      handleDetailFile,
      fileList,
      detailFileList,
      srcList,
      mainSrcList,
      formRef,
      showModal: showModalRef,
      showPreviewModal: showPreviewModalRef,
      showPhoneModal: showPhoneModalRef,
      previewImageUrl: previewImageUrlRef,
      findList,
      columns: createColumns({
        previewProduct(row) {
          showPhoneModalRef.value = true;
          if (row.detailPicture) {
            srcList.value = (row.detailPicture.split("|") ?? []).map(
              (item) => ({
                url: item,
              })
            );
          } else {
            srcList.value = [];
          }
          if (row.mainPicture) {
            mainSrcList.value = (row.mainPicture.split("|") ?? []).map(
              (item) => ({
                url: item,
              })
            );
          } else {
            mainSrcList.value = [];
          }
          currentPrdouct.value = row;
        },
        editProduct(row) {
          if (row.mainPicture) {
            fileList.value = (row.mainPicture.split("|") ?? []).map((item) => ({
              url: item,
              status: "finished",
            }));
          }
          if (row.detailPicture) {
            detailFileList.value = (row.detailPicture.split("|") ?? []).map(
              (item) => ({
                url: item,
                status: "finished",
              })
            );
          }
          showModalRef.value = true;
          addPrdouct.value = row;
        },
        changeStatus(row) {
          axios({
            method: "post",
            url: "/productInfo/changeStatus",
            params: { id: row.id },
          }).then(function (response) {
            if (response.data.code === 200) {
              message.success("保存成功");
              findList(queryData.value);
            }
          });
        },
      }),

      save(row) {
        formRef.value.validate((errors) => {
          if (!errors) {
            if (fileList.value.length === 0) {
              message.error("请上传主图");
            } else {
              row.mainPicture = fileList.value
                .map((element) => {
                  return element.url;
                })
                .join("|");

              row.detailPicture = detailFileList.value
                .map((element) => {
                  return element.url;
                })
                .join("|");

              if (row.id) {
                axios({
                  method: "post",
                  url: "/productInfo/update",
                  data: row,
                }).then(function (response) {
                  if (response.data.code === 200) {
                    message.success("保存成功");
                    findList(queryData.value);
                    showModalRef.value = false;
                  }
                });
              } else {
                axios({
                  method: "post",
                  url: "/productInfo/save",
                  data: row,
                }).then(function (response) {
                  if (response.data.code === 200) {
                    message.success("保存成功");
                    findList(queryData.value);
                    showModalRef.value = false;
                  }
                });
              }
            }
          }
        });
      },

      clear() {
        queryData.value = cloneDeep(initQueryData);
      },

      rules: {
        name: {
          required: true,
          trigger: "input",
          message: "请输入名称",
        },
        price: {
          type: "number",
          required: true,
          trigger: "change",
          message: "请输入原价",
        },
        agentPrice: {
          type: "number",
          required: true,
          trigger: "change",
          message: "请输入代理商价",
        },
        companyPrice: {
          type: "number",
          required: true,
          trigger: "change",
          message: "请输入分公司价",
        },
        stock: {
          type: "number",
          required: true,
          trigger: "change",
          message: "请输入库存",
        },
        sort: {
          type: "number",
          required: true,
          trigger: "change",
          message: "请输入排序",
        },
      },
    };
  },
});
</script>

<template>
  <n-form
    inline
    label-placement="left"
    :model="queryData"
    class="formStyle"
    style="width: 60%"
  >
    <n-form-item label="名称" path="name">
      <n-input v-model:value="queryData.name" placeholder="输入名称" />
    </n-form-item>
    <n-form-item :span="12" label="状态" path="status">
      <n-select
        :clearable="true"
        v-model:value="queryData.status"
        placeholder="请选择"
        :options="statusOptions"
      />
    </n-form-item>
    <n-form-item>
      <n-button style="margin-left: 20px" @click="clear()"> 重置 </n-button>
      <n-button
        type="info"
        style="margin-left: 20px"
        @click="findList(queryData)"
      >
        查询
      </n-button>
    </n-form-item>
  </n-form>

  <div class="divStyle">
    <n-button type="info" @click="showModal = true">新增</n-button>
  </div>

  <n-data-table
    class="tableStyle"
    :columns="columns"
    :data="data"
    :pagination="true"
    :bordered="true"
    :scroll-x="1800"
  />

  <n-modal
    v-model:show="showModal"
    :mask-closable="false"
    preset="dialog"
    :show-icon="false"
    @after-leave="(fileList = []), (detailFileList = []), (addPrdouct = {})"
    style="max-height: 600px; overflow-y: scroll; width: 500px"
  >
    <n-form
      ref="formRef"
      :label-width="80"
      :rules="rules"
      :model="addPrdouct"
      label-placement="left"
      label-width="auto"
      require-mark-placement="right-hanging"
      :style="{
        'padding-top': '30px',
        'padding-left': '30px',
      }"
    >
      <n-grid x-gap="12" :cols="1">
        <n-gi>
          <n-form-item label="名称" path="name" style="width: 294px">
            <n-input v-model:value="addPrdouct.name" placeholder="请输入" />
          </n-form-item>
        </n-gi>
        <n-gi>
          <n-form-item label="类型" path="type">
            <n-radio-group v-model:value="addPrdouct.type" :default-value="1">
              <n-space>
                <n-radio :value="1"> 普通商品 </n-radio>
                <n-radio :value="2"> 代理商礼包 </n-radio>
                <n-radio :value="3"> 分公司礼包 </n-radio>
                <n-radio :value="4"> 免费商品 </n-radio>
                <n-radio :value="5"> 秒杀商品 </n-radio>
              </n-space>
            </n-radio-group>
          </n-form-item>
        </n-gi>
        <n-gi>
          <n-form-item label="状态" path="status">
            <n-radio-group v-model:value="addPrdouct.status" :default-value="1">
              <n-space>
                <n-radio :value="1"> 上架 </n-radio>
                <n-radio :value="0"> 下架 </n-radio>
              </n-space>
            </n-radio-group>
          </n-form-item>
        </n-gi>
        <n-gi>
          <n-form-item label="原价" path="price">
            <n-input-number
              v-model:value="addPrdouct.price"
              placeholder="请输入"
              :disabled="addPrdouct.type == 4"
            />
          </n-form-item>
        </n-gi>
        <n-gi v-if="!(addPrdouct.type == 4 || addPrdouct.type == 5)">
          <n-form-item label="代理商价" path="agentPrice">
            <n-input-number
              v-model:value="addPrdouct.agentPrice"
              placeholder="请输入"
            />
          </n-form-item>
        </n-gi>
        <n-gi v-if="!(addPrdouct.type == 4 || addPrdouct.type == 5)">
          <n-form-item label="分公司价" path="companyPrice">
            <n-input-number
              v-model:value="addPrdouct.companyPrice"
              placeholder="请输入"
            />
          </n-form-item>
        </n-gi>

        <n-gi v-if="addPrdouct.type == 5">
          <n-form-item label="秒杀价" path="killPrice">
            <n-input-number
              v-model:value="addPrdouct.killPrice"
              placeholder="秒杀商品必填"
            />
          </n-form-item>
        </n-gi>
        <n-gi v-if="addPrdouct.type == 5">
          <n-form-item label="秒杀开始时间" path="beginTime">
            <n-date-picker
              v-model:value="addPrdouct.beginTime"
              type="datetime"
              clearable
            />
          </n-form-item>
        </n-gi>
        <n-gi>
          <n-form-item label="库存" path="stock">
            <n-input-number
              v-model:value="addPrdouct.stock"
              placeholder="请输入"
            />
          </n-form-item>
        </n-gi>
        <n-gi>
          <n-form-item label="排序" path="sort">
            <n-input-number
              v-model:value="addPrdouct.sort"
              placeholder="请输入"
            />
          </n-form-item>
        </n-gi>
        <n-gi>
          <n-form-item label="简要描述" path="description" style="width: 294px">
            <n-input
              type="textarea"
              v-model:value="addPrdouct.description"
              placeholder="请输入"
            />
          </n-form-item>
        </n-gi>
      </n-grid>
      <n-form-item label="主图" path="mainPicture">
        <n-upload
          class="uploadStyle"
          action="/api/cosFile/upload"
          v-model:file-list="fileList"
          list-type="image-card"
          @preview="handlePreview"
          :on-finish="handleFile"
        />
      </n-form-item>
      <n-form-item label="商品详情" path="detailPicture">
        <n-upload
          class="uploadStyle"
          action="/api/cosFile/upload"
          v-model:file-list="detailFileList"
          list-type="image-card"
          @preview="handlePreview"
          :on-finish="handleDetailFile"
        />
      </n-form-item>
      <div style="display: flex; justify-content: flex-end; margin-top: 20px">
        <n-button style="margin-right: 20px" @click="showModal = false">
          取消
        </n-button>
        <n-button type="primary" @click="save(addPrdouct)"> 保存 </n-button>
      </div>
    </n-form>
  </n-modal>

  <n-modal v-model:show="showPreviewModal" preset="card" style="width: 600px">
    <img :src="previewImageUrl" style="width: 100%" />
  </n-modal>

  <n-modal v-model:show="showPhoneModal" preset="card" style="width: 600px">
    <div class="phoneStyle">
      <div style="max-height: 504px; overflow: auto">
        <n-carousel autoplay draggable class="carouselStyle">
          <div style="height: 100%" v-for="item in mainSrcList">
            <img class="carousel-img" :src="item.url" />
          </div>
        </n-carousel>
        <n-card style="margin: 8px 0px 0px 148px; width: 254px">
          <div>
            <span style="color: red; font-size: larger; font-weight: bold">{{
              currentPrdouct.price
            }}</span>
            <span style="color: red"> 积分 </span>
          </div>
          <div style="font-weight: bold">{{ currentPrdouct.name }}</div>
          <div style="color: #7e7e7e">{{ currentPrdouct.description }}</div>
        </n-card>
        <div style="font-weight: bold; margin: 8px 0px 0px 150px">图文详情</div>
        <div
          id="image-scroll-container"
          style="
            width: 263px;
            display: flex;
            flex-direction: column;
            margin: 10px 0px 0px 143px;
          "
        >
          <div v-for="item in srcList">
            <img
              style="width: 100%; height: 100%; display: block"
              :src="item.url"
            />
          </div>
        </div>
      </div>
    </div>
  </n-modal>
</template>

<style>
::-webkit-scrollbar {
  display: none;
}

.carousel-img {
  width: 100%;
  height: 100%;
}

.n-card > .n-card__content:first-child,
.n-card > .n-card__footer:first-child {
  padding: 10px;
}

.tableStyle {
  margin-left: 20px;
  width: 94%;
}

.formStyle {
  margin: 40px 0px 0px 30px;
}

.n-form.n-form--inline .n-form-item {
  width: 100%;
  margin-right: 18px;
}

.divStyle {
  display: flex;
  justify-content: flex-end;
  width: 94%;
  margin: -44px 0px 10px 0px;
}

.uploadStyle {
  margin: 20px;
}

.phoneStyle {
  background-image: url(/img/phone.jpg);
  background-position: center;
  background-repeat: no-repeat;
  width: 550px;
  height: 640px;
  background-size: 400px;
  padding-top: 107px;
}

.carouselStyle {
  width: 263px;
  height: 263px;
  margin-left: 143px;
}
</style>
